package cc.fine.svc.main.service.impl.rel;

import cc.fine.svc.config.redis.utils.RedisCache;
import cc.fine.svc.main.bean.po.RelUserVideoCollect;
import cc.fine.svc.main.bean.po.TblCollect;
import cc.fine.svc.main.mapper.RelUserVideoCollectMapper;
import cc.fine.svc.main.service.VideoCountService;
import cc.fine.svc.main.service.rel.RelUserVideoCollectService;
import cc.fine.svc.main.service.tbl.TblUserCountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyihe
 * @since 2023-10-25
 */
@Service
@Transactional
public class RelUserVideoCollectServiceImpl extends ServiceImpl<RelUserVideoCollectMapper, RelUserVideoCollect> implements RelUserVideoCollectService {

    @Autowired
    private TblUserCountService userCountService;

    @Autowired
    private VideoCountService videoCountService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void collect(String collectId, String videoId) {
        // 检查是否收藏过了
        QueryWrapper<RelUserVideoCollect> w = new QueryWrapper<>();
        w.eq("collect_id", collectId);
        w.eq("video_id", videoId);

        // 没有被收藏过就收藏该视频
        if (list(w).isEmpty()) {
            RelUserVideoCollect rel = new RelUserVideoCollect();
            rel.setCollectId(collectId);
            rel.setVideoId(videoId);
            save(rel);

            videoCountService.increaseCollect(videoId);
        }

    }

    @Override
    public void disCollect(String collectId, String videoId) {
        // 检查是否收藏过了
        QueryWrapper<RelUserVideoCollect> w = new QueryWrapper<>();
        w.eq("collect_id", collectId);
        w.eq("video_id", videoId);

        // 被收藏过就取消收藏该视频
        if (!list(w).isEmpty()) {
            remove(w);

            videoCountService.reduceCollect(videoId);


        }
    }

    @Override
    public List<TblCollect> searchCollect(String userId, String videoId) {
       List<TblCollect> res = baseMapper.selectCollect(userId, videoId);
       if (res == null) res = new ArrayList<>();
       return res;
    }
}
